package org.ainlolcat.ainscience.column.custom;

import org.ainlolcat.ainscience.column.Column;
import org.ainlolcat.ainscience.column.CustomColumn;
import org.ainlolcat.ainscience.entity.Entity;
import org.ainlolcat.ainscience.matrix.MatrixFileParser;
import org.ainlolcat.ainscience.tools;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Hashtable;

/**
 * @author ainlolcat
 * Date: 12/21/11
 */
public class IntegrateCustomColumn extends CustomColumn {
    private static Logger log = Logger.getLogger(IntegrateCustomColumn.class);

    public IntegrateCustomColumn(){}

    public Column generateColumn(Hashtable<String, String> params, Entity entity) {
        setType(MatrixFileParser.MATRIX_DELIMETER_TYPE_DOUBLE);
        if (params.containsKey("column")){
            Integer numcx = tools.parseInteger(params.get("column"));
            Column cy = entity.getColumnByOrder(numcx);
            axis = cy.getAxis();
            if ( cy != null ){
                Column cx = entity.getXColumn( cy.getAxis() );
                if ( cx!=null && cx.isNumeric() && cy.isNumeric() ){
                    double[] dcx = cx.getDoubleRepresentation();
                    double[] dcy = cy.getDoubleRepresentation();
                    double integral = 0;
                    values = new ArrayList();
                    values.add(integral);
                    for (int i=1;i<dcx.length;i++){
                        integral+=(dcx[i]-dcx[i-1])*(dcy[i]+dcy[i-1])/2;
                        values.add(integral);
                    }
                    return this;
                } else {
                    throw new IllegalArgumentException("Cannot create IntegrateCustomColumn because X column is null or one of column has no numeric type");
                }
            } else {
                throw new IllegalArgumentException("Cannot create IntegrateCustomColumn because Y column is null");
            }
        } else {
            throw new IllegalArgumentException("Cannot create IntegrateCustomColumn due missing column parameter");
        }
    }
}
